<template>
	<view>
		<view class="upload">
			<block v-for="(upload,index) in uploads" :key="index">
				<view class="uplode-file">
					<image v-if="types == 'image'" class="uploade-img" :src="upload" :data-src="upload" @tap="previewImage"></image>
					<image v-if="types == 'image'" class="clear-one-icon" :src="clearIcon" @tap="delImage(index)"></image>
					<video v-if="types == 'video'" class="uploade-img" :src="upload" controls></video>
					<image v-if="types == 'video'" class="clear-one-icon" :src="clearIcon" @tap="delImage(index)"></image>
					<u-line-progress
						v-if="showProgress && progress > 0"
						:show-percent="false"
						height="16"
						class="u-progress"
						:percent="progress"
					></u-line-progress>
				</view>
			</block>
			<view v-if="uploads.length < uploadCount" :class="uploadIcon ? 'uploader-icon' : 'uploader-input-box'">
				<view v-if="!uploadIcon" class="uploader-input" @tap="chooseUploads"></view>
				<image v-else class="image-cion" :src="uploadIcon" @tap="chooseUploads"></image>
			</view>
		</view>	
		<button type="primary" v-if="types == 'image' && !autoUpload" @tap="unifiedUpload">上传</button>
	</view>
</template>

<script>
	export default{
		props: {
			//  是否显示进度条
			showProgress: {
				type: Boolean,
				default: true
			},
			types: {
				type: String,
				default: 'image'
			},
			dataList: {
				type: Array,
				default: function() {
					return []
				}
			},
			clearIcon: {
				type: String,
				default: 'http://img1.imgtn.bdimg.com/it/u=451604666,2295832001&fm=26&gp=0.jpg'
			},
			uploadIcon: {
				type: String,
				default: ''
			},
			uploadUrl: {
				type: String,
				default: ''
			},
			deleteUrl: {
				type: String,
				default: ''
			},
			uploadCount: {
				type: Number,
				default: 1
			},
			//上传图片大小 默认3M
			upload_max: {
				type: Number,
				default: 99
			},
			autoUpload: {
				type: Boolean,
				default: false
			},
			header:{
				type: Object,
				default: () => {}
			}
		},
		data(){
			return {
				//上传的图片地址
				uploadImages: [],
				//展示的图片地址
				uploads: [],
				// 超出限制数组
				exceeded_list: [],
				progress: 0	// 上传进度
			}
		},
		watch:{
			dataList:{
				handler(val){
					console.log('dataList数据变化',val)
					if(val == undefined){
						
					}else{
						this.uploads = val;	
					}
				},
				immediate: true
			}
		},
		methods:{
			previewImage (e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.dataList
				})
			},
			chooseUploads(){
				// console.log(this.header)
				switch (this.types){
					case 'image': 
						uni.chooseImage({
							count: this.uploadCount - this.uploads.length, //默认9
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], //从相册选择
							success: (res) => {
								console.log(`%c 组件easey-upload上传`,"color: #00aa00",res)
								// this.testUpload(res);
								this.handleUpload(res)
								
							},
							fail: (err) => {
								// uni.showModal({
								// 	content: '取消上传',
								// 	showCancel:false
								// });
							}
						});
					break;
					case 'video' :
						var that = this;
						uni.chooseVideo({
							sourceType: ['camera', 'album'],
							success: (res) => {
								console.log(res)
								if(Math.ceil(res.size / 1024) < that.upload_max * 1024){
									that.uploads.push(res.tempFilePath)
									const task = uni.uploadFile({
										url: that.uploadUrl, //仅为示例，非真实的接口地址
										filePath: res.tempFilePath,
										name: 'file',
										fileType:"video",
										header:that.header || {},
										//请求参数
										formData: {
											'user': 'test'
										},
										success: (uploadFileRes) => {
											that.$emit('successVideo',uploadFileRes)
										},
										fail(res) {
											that.$emit('failUpload',that.types)
											that.uploads.pop();
											console.error("上传失败",JSON.stringify(res))
											// uni.showModal({
											// 	title:'视频上传失败',
											// 	content:JSON.stringify(res)
											// })
										}
									});
									task.onProgressUpdate(res => {
										if (res.progress > 0) {
											// console.log(res)
											this.progress = res.progress;
											// this.$emit('on-progress', res, this.uploads);
										}
									});
								}else {
									uni.showModal({
										title: '提示',
										content: `第${[...new Set(that.exceeded_list)].join(',')}张视频超出限制${that.upload_max}MB,已过滤`
									});
								}
							},
							fail: (err) => {
								uni.showModal({
									content: JSON.stringify(err)
								});
							}
						});
					break;
				}
			},
			/**
			 * 测试上传
			 * @description 支付宝小程序开发工具图片上传返回 tempFilePaths数组，
			 * tempFiles对象返回获取undefined，不能限制图片大小；
			 * 2021/08/03 yxq
			 */
			testUpload(res){
				for(let i = 0; i< res.tempFilePaths.length; i++){
					if(true){
						this.uploads.push(res.tempFilePaths[i])
						if(this.autoUpload){
							this.uploadFile(res.tempFilePaths[i])
						}else{
							this.uploadImages.push(res.tempFilePaths[i]);
						}
					}else {
						this.exceeded_list.push(i === 0 ? 1 : i + 1);
						uni.showModal({
							title: '提示',
							content: `第${[...new Set(this.exceeded_list)].join(',')}张图片超出限制${this.upload_max}MB,已过滤`
						});
					}
				}
			},
			handleUpload(res){
				console.log(res);
				let arr = res.tempFilePaths;
				let that = this;
				for(let i = 0; i< arr.length; i++){
					if(typeof arr[i] == "string"){
						uni.getFileInfo({
							filePath:arr[i],
							success(file) {
								console.log(file)
								if(file.size < that.upload_max * 1024 * 1024){
									that.uploads.push(arr[i])
									if(that.autoUpload){
										that.uploadFile(arr[i])
									}
								}else {
									that.exceeded_list.push(i === 0 ? 1 : i + 1);
									uni.showModal({
										title: '提示',
										content: `第${[...new Set(that.exceeded_list)].join(',')}张图片超出限制${that.upload_max}MB,已过滤`
									});
								}
							}
						})
					}
				}
			},
			
			delImage(index){
				//第一个是判断app或者h5的 第二个是判断小程序的
				console.log(this.uploads);
				if(this.uploads[index].substring(0,4) !== 'http' || this.uploads[index].substring(0,11) == 'http://tmp/' 
				 || this.uploads[index].substring(0,16) === 'https://resource'){
					this.uploads.splice(index,1)
					this.$emit("delSuccess",index,this.types)
					return;
				};
				if(!this.deleteUrl) {
					uni.showModal({
						content: '请填写删除接口'
					});
					return;
				};
				uni.request({
					url: this.deleteUrl,
					method: 'DELETE',
					data: {
						image: this.dataList[index]
					},
					success: res => {
						if(res.data.status == 1) {
							uni.showToast({
								title: '删除成功'
							})
							this.uploads.splice(index,1)
						}
					},
				});
				
				this.$emit("delSuccess",this.dataList)
			},
			uploadFile(path){
				console.log(this.uploads)
				var that = this;
				let param = {
					url: that.uploadUrl, //仅为示例，非真实的接口地址
					filePath: path,
					name: 'file',
					// fileName: 'file',
					header: that.header,
					fileType: "image",
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						if(JSON.parse(uploadFileRes.data).url){
							that.uploadImages.push(JSON.parse(uploadFileRes.data).url);
						}
						that.$emit('successImage',uploadFileRes)
					},
					fail(res) {
						that.$emit('failUpload',that.types)
						// that.uploads.pop();
						// console.error("上传失败",JSON.stringify(res))
						// uni.showModal({
						// 	title:'图片上传失败',
						// 	content:JSON.stringify(res)
						// })
					},
					complet(res){
						console.log('complet',res)
					}
				};
				console.log(param);
				uni.uploadFile(param);
				//let uploadParam = 
				// console.log(uploadParam)
				// uni.uploadFile(uploadParam);
				// uploadParam.onProgressUpdate(res => {
				// 	if (res.progress > 0) {
				// 		// console.log(res)
				// 		this.progress = res.progress;
				// 		// this.$emit('on-progress', res, this.uploads);
				// 	}
				// });			
			},
			unifiedUpload(){
				if(!this.uploadUrl) {
					uni.showModal({
						content: '请填写上传接口'
					});
					return;
				};
				for (let i of this.uploadImages) {
					this.uploadFile(i)
				}
			}
		}
	}
</script>

<style scoped>
	.upload {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
	}
	.uplode-file {
		margin: 10upx;
		width: 140upx;
		height: 140upx;
		position: relative;
	}
	.uploade-img {
		display: block;
		width: 140upx;
		height: 140upx;
	}
	.clear-one{
		position: absolute;
		top: -10rpx;
		right: 0;
	}
	.clear-one-icon{
		position: absolute;
		width: 20px;
		height: 20px;
		top: -8px;
		right: -8px;
		z-index: 9;
	}
	.uploader-input-box {
		position: relative;
		margin:10upx;
		width: 140upx;
		height: 140upx;
		border: 2upx dashed #F2F2F2;
	}
	.uploader-input-box:before,
	.uploader-input-box:after {
		content: " ";
		position: absolute;
		top: 50%;
		left: 50%;
		-webkit-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
		background-color: #31CAD9;
	}
	.uploader-input-box:before {
		width: 5upx;
		height: 30upx;
	}
	.uploader-input-box:after {
		width: 30upx;
		height: 5upx;
	}
	.uploader-input-box:active {
		border-color: #999999;
	}
	.uploader-input-box:active:before,
	.uploader-input-box:active:after {
		background-color: #999999;
	}
	.uploader-input {
		position: absolute;
		z-index: 1;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
	}
	.uploader-icon{
	    position: relative;
	    margin: 10rpx;
	    width: 140rpx;
	    height: 140rpx;
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    border: #F2F2F2 3rpx dashed;
	}
	.uploader-icon .image-cion{
		width: 60%;
		height: 60%;
	}
	.u-progress {
		position: absolute;
		bottom: 10rpx;
		left: 8rpx;
		right: 8rpx;
		z-index: 9;
		width: auto;
	}</style>
